package com.example.speeddating.controller;

import com.example.speeddating.common.BaseResponse;
import com.example.speeddating.common.RespGenerator;
import com.example.speeddating.entity.Like;
import com.example.speeddating.entity.TokenEntity;
import com.example.speeddating.exception.CommonException;
import com.example.speeddating.annotaion.LoginUser;
import com.example.speeddating.annotaion.TokenCheck;
import com.example.speeddating.service.LikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 *
 * @author tina
 * @since 2023-06-28 11:14:33
 */
@RestController
public class LikeController {

    @Autowired
    private LikeService likeService;

    /**
     * 用户点赞 文章/评论
     * @param jsonString
     * @return
     */
    @TokenCheck(roles = "user")
    @PostMapping("/user/like")
    public BaseResponse like(@LoginUser TokenEntity tokenEntity, @RequestBody HashMap<String,Object> jsonString){
        Like like = new Like();
        like.setUserId(tokenEntity.getId());
        Object articleId = jsonString.get("articleId");
        if (articleId!=null){
            like.setArticleId(Long.valueOf(articleId.toString()));
            like.setCommentId(null);
        }
        Object commentId = jsonString.get("commentId");
        if (commentId!=null){
            like.setArticleId(null);
            like.setCommentId(Long.valueOf(commentId.toString()));
        }
        return RespGenerator.returnOK(likeService.insertLike(like));
    }

    /**
     * 取消点赞
     * @param
     * @return
     */
    @TokenCheck(roles = "user")
    @DeleteMapping("/user/unlike")
    public BaseResponse unlike(@LoginUser TokenEntity tokenEntity,@RequestBody HashMap<String,Object> jsonString){
        if (tokenEntity==null){
            throw new CommonException("您无权访问");
        }
        Object articleIdstr = jsonString.get("articleId");
        Object commentIdstr = jsonString.get("commentId");
        Long articleId = null;
        Long commentId = null;
        if (articleIdstr==null&&commentIdstr==null){
            throw new CommonException("参数错误");
        }
        if (articleIdstr!=null){
            articleId = (Long.valueOf(articleIdstr.toString()));
        }
        if (commentIdstr!=null){
            commentId = (Long.valueOf(commentIdstr.toString()));
        }
        return RespGenerator.returnOK(likeService.deleteLike(articleId,commentId,tokenEntity.getId()));
    }


}
